<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useAlertStore } from '@/stores'
import { getIdleRobots } from '@/api/robot'
import { dispatchAlert } from '@/api/alert'
import router from '@/router'

// 在线机器人数据
const onlineRobots = ref([])
const robotTotal = ref(0)
const robotCurrentPage = ref(1)
const robotPageSize = ref(5)
const alertStore = useAlertStore()

// 当前警情信息
const alertInfo = ref(null)
const selectedRobot = ref(null)

const tableRowClassName = ({ row }) => {
  return row.batteryLevel < 30 ? 'row-low-battery' : ''
}

const getEmergencyLevelTag = (status) =>
  ({ 紧急: 'danger', 警告: 'warning', 预警: 'info' })[status] || ''

const robotFilterForm = reactive({ robotName: '' })

const searchRobots = () => {
  queryIdleRobots()
  ElMessage.success('搜索成功')
}

const handleSelectRobot = (robot) => {
  selectedRobot.value = robot
}

// 提交分配
const submitAssignment = async () => {
  if (!selectedRobot.value) {
    ElMessage.warning('请至少选择一个机器人')
    return
  }

  const getConfirmMessage = () => {
    const alertNo = alertInfo.value.alertNo
    const robotName = selectedRobot.value?.robotName
    return `确认将警情 ${alertNo} 分配给机器人 ${robotName} 吗？`
  }

  const payload = {
    alertId: alertInfo.value?.id ?? null,
    robotId: selectedRobot.value?.id ?? null
  }

  try {
    await ElMessageBox.confirm(getConfirmMessage(), '确认分配', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 立即显示加载状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在分配任务，请稍候...',
      customClass: 'fancy-loading', // 确保添加这个类
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 模拟乐观更新：假设分配成功，提前清空数据
    const previousAlertInfo = { ...alertInfo.value }
    const previousSelectedRobot = { ...selectedRobot.value }
    alertStore.setAlertInfo({})
    selectedRobot.value = null

    try {
      // 发送请求并设置超时（例如 30 秒）
      const dispatchPromise = dispatchAlert(payload)
      const timeoutPromise = new Promise((_, reject) =>
        setTimeout(() => reject(new Error('请求超时')), 30000)
      )
      await Promise.race([dispatchPromise, timeoutPromise])

      loadingInstance.close()
      router.push('/robot/monitor')
      ElMessage.success('分配成功')
    } catch (error) {
      // 请求失败，回滚状态
      alertStore.setAlertInfo(previousAlertInfo)
      selectedRobot.value = previousSelectedRobot
      ElMessage.error(`分配失败: ${error.message || '未知错误'}`)
      loadingInstance.close()
    }
  } catch (error) {
    // 用户取消确认时不做任何操作
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 取消分配
const cancelAssignment = () => {
  ElMessageBox.confirm('确定要取消本次分配操作吗？', '取消操作', {
    confirmButtonText: '确定',
    cancelButtonText: '返回',
    type: 'info'
  })
    .then(() => {
      alertStore.setAlertInfo({})
      history.back()
    })
    .catch(() => { })
}

const queryIdleRobots = async () => {
  const { data } = await getIdleRobots(
    robotCurrentPage.value,
    robotPageSize.value,
    robotFilterForm.robotName
  )
  robotTotal.value = data.total
  onlineRobots.value = data.list
}

onMounted(() => {
  alertInfo.value = alertStore.alertInfo
  queryIdleRobots()
})

onUnmounted(() => {
  alertStore.setAlertInfo({})
})
</script>

<template>
  <div class="assignment-page">
    <!-- 警情信息头部 -->
    <section class="alarm-info-section">
      <el-card shadow="hover" class="alarm-card">
        <template #header>
          <div class="alarm-header">
            <h2>警情分配</h2>
            <el-tag type="danger" effect="dark" round>{{
              alertInfo?.status
            }}</el-tag>
          </div>
        </template>
        <el-descriptions :column="2" border class="alarm-descriptions">
          <el-descriptions-item label="警情编号">{{
            alertInfo?.alertNo
          }}</el-descriptions-item>
          <el-descriptions-item label="警情类型">
            <el-tag type="danger">{{ alertInfo?.alertType }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地点">{{
            alertInfo?.location
          }}</el-descriptions-item>
          <el-descriptions-item label="报警时间">{{
            alertInfo?.createdTime
          }}</el-descriptions-item>
          <el-descriptions-item label="紧急程度">
            <el-tag
              :type="getEmergencyLevelTag(alertInfo?.emergencyLevel)"
              effect="dark"
              round
            >
              {{ alertInfo?.emergencyLevel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="环境描述">{{
            alertInfo?.environmentDesc
          }}</el-descriptions-item>
          <el-descriptions-item label="危险物品">{{
            alertInfo?.dangerousGoods
          }}</el-descriptions-item>
          <el-descriptions-item label="事故描述">{{
            alertInfo?.incidentDesc
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </section>

    <!-- 分配区域 -->
    <section class="assignment-section">
      <el-card shadow="hover" class="selection-card">
        <template #header>
          <div class="selection-header">
            <h3><i class="el-icon-robot"></i> 选择救援机器人</h3>
            <div class="selection-summary" v-if="selectedRobot">
              已选择:
              <el-tag type="success" effect="dark">{{
                selectedRobot.robotName
              }}</el-tag>
            </div>
          </div>
        </template>

        <!-- 机器人筛选表单 -->
        <el-form :model="robotFilterForm" inline class="filter-form">
          <el-form-item label="机器人名称">
            <el-input
              v-model="robotFilterForm.robotName"
              placeholder="输入名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchRobots">
              <el-icon><i-ep-Search></i-ep-Search></el-icon>
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 机器人列表 -->
        <el-table
          :data="onlineRobots"
          style="width: 100%; min-height: 250px"
          size="medium"
          highlight-current-row
          @current-change="handleSelectRobot"
          :max-height="400"
          stripe
          class="robot-table"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="radio" width="50" align="center" />
          <el-table-column prop="id" label="ID" width="100" align="center" />
          <el-table-column
            prop="robotName"
            label="名称"
            min-width="180"
            align="center"
          />
          <el-table-column
            prop="batteryLevel"
            label="电量"
            width="200"
            align="center"
          >
            <template #default="{ row }">
              <el-progress
                :percentage="row.batteryLevel"
                :stroke-width="8"
                :color="[
                  { color: '#F56C6C', percentage: 30 },
                  { color: '#E6A23C', percentage: 70 },
                  { color: '#67C23A', percentage: 100 }
                ]"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="location"
            label="位置"
            min-width="220"
            align="center"
            show-overflow-tooltip
          />
        </el-table>

        <!-- 机器人分页 -->
        <el-pagination
          v-model:current-page="robotCurrentPage"
          v-model:page-size="robotPageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="robotTotal"
          layout="total, sizes, prev, pager, next"
          @size-change="queryIdleRobots"
          @current-change="queryIdleRobots"
          class="pagination"
        />
      </el-card>
    </section>

    <!-- 底部操作栏 -->
    <section class="action-section">
      <div class="action-container">
        <div class="assignment-summary">
          <div class="selected-item" v-if="selectedRobot">
            <span class="label">选中机器人:</span>
            <el-tag type="success" effect="dark" class="selected-tag">{{
              selectedRobot.robotName
            }}</el-tag>
            <span class="details">电量: {{ selectedRobot.batteryLevel }}%</span>
          </div>
          <div class="empty-selection" v-else>
            <el-icon><i-ep-warning /></el-icon>
            <span>请选择一个机器人</span>
          </div>
        </div>
        <div class="action-buttons">
          <el-button @click="cancelAssignment" class="cancel-btn"
            >取消</el-button
          >
          <el-button
            type="primary"
            :disabled="!selectedRobot"
            @click="submitAssignment"
            class="submit-btn"
          >
            确认分配
          </el-button>
        </div>
      </div>
    </section>
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/scss/abstracts/mixins';

.assignment-page {
  padding: 2.4rem;
  background: linear-gradient(to bottom, #eef2f6, #f5f7fa);
  min-height: 100vh;
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.alarm-info-section {
  margin-bottom: 2.5rem;

  .alarm-card {
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
    // 移除浮动效果
    // transition: transform 0.3s;
    // &:hover {
    //   transform: translateY(-4px);
    // }

    .alarm-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 2rem;
        font-weight: 600;
        color: #1f2a44;
      }

      .el-tag {
        font-size: 1.6rem;
        padding: 4px 12px;
      }
    }

    .alarm-descriptions {
      margin-top: 1.6rem;

      :deep(.el-descriptions__label) {
        background: #f8f9fc;
        color: #1f2a44;
        font-weight: 500;
        padding: 12px;
        font-size: 1.6rem;
      }

      :deep(.el-descriptions__content) {
        padding: 12px;
        font-size: 1.6rem;
        .el-tag {
          font-size: inherit;
        }
      }
    }
  }
}

.assignment-section {
  .selection-card {
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);

    .selection-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 2rem;
        font-weight: 600;
        color: #1f2a44;
        display: flex;
        align-items: center;
        gap: 8px;

        .el-icon-robot {
          font-size: 2rem;
          color: #4834d4;
        }
      }

      .selection-summary {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 1.6rem;
        color: #606266;

        .el-tag {
          font-weight: 500;
        }
      }
    }

    .filter-form {
      margin-bottom: 16px;

      .el-input {
        width: 200px;
        .el-input__wrapper {
          border-radius: 8px;
        }
      }

      .el-button--primary {
        background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
        border: none;
        border-radius: 8px;
        padding: 10px 20px;
        transition: opacity 0.3s;

        &:hover {
          opacity: 0.9;
        }
      }
    }

    .robot-table {
      :deep(.el-table__header th) {
        font-weight: 600;
        font-size: 1.6rem;
      }

      :deep(.el-table__row) {
        font-size: 1.6rem;
      }
    }

    .pagination {
      margin-top: 16px;
      justify-content: flex-end;

      :deep(.el-pager li.is-active) {
        background: #4834d4;
        color: #fff;
      }
    }
  }
}

.action-section {
  position: sticky;
  bottom: 16px;
  z-index: 10;

  .action-container {
    background: #fff;
    padding: 16px 24px;
    border-radius: 12px;
    box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    animation: slideUp 0.3s ease-out;

    .assignment-summary {
      .selected-item {
        display: flex;
        align-items: center;
        gap: 12px;

        .label {
          font-weight: 500;
          color: #1f2a44;
        }

        .selected-tag {
          padding: 4px 12px;
          font-weight: 500;
        }

        .details {
          color: #606266;
          font-size: 14px;
        }
      }

      .empty-selection {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #e6a23c;
        font-size: 14px;

        .el-icon {
          font-size: 18px;
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 16px;

      .cancel-btn {
        border-radius: 8px;
        padding: 10px 20px;
        transition: all 0.3s;

        &:hover {
          background: #f5f5f5;
          color: #e6a23c;
        }
      }

      .submit-btn {
        background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
        border: none;
        border-radius: 8px;
        padding: 10px 24px;
        transition: all 0.3s;

        &:hover:not(:disabled) {
          opacity: 0.9;
          transform: scale(1.05);
        }

        &:disabled {
          background: #dcdfe6;
        }
      }
    }
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}
</style>
